from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
from asgiref.sync import async_to_sync

class ChatConsumer(WebsocketConsumer):


    # 负责与客户端建立连接
    def websocket_connect(self,message):
        #有客户端来向后端发送websocket连接的请求时，自动触发。
        #服务端允许和客户端创建连接(握手)。
        print("链接成功")
        self.accept()
        # 获取路由匹配中的组名
        user = self.scope.get('user')
        group = self.scope['url_route']['kwargs']['group']
        room_name = f"char_{min(user.id, int(group))}_{max(user.id, int(group))}"
        print(room_name)
        async_to_sync(self.channel_layer.group_add)(room_name,self.channel_name)
    # 负责接收客户端建立连接
    def websocket_receive(self,message):
        #浏览器基于websocket向后端发送数据，自动触发接收消息。
        # message 是一个字典
        user = self.scope.get('user')
        group = self.scope['url_route']['kwargs']['group']
        room_name = f"char_{min(user.id, int(group))}_{max(user.id, int(group))}"
        async_to_sync(self.channel_layer.group_send)(room_name,{'type':'send_msg','message':message})
        #self.close()

    def send_msg(self,event):
        text = event['message']['text']
        self.send(text)

    # 负责断开与客户端的连接
    def websocket_disconnect(self,message):
        #客户端与服务端断开连接时，自动触发。
        user = self.scope.get('user')
        group = self.scope['url_route']['kwargs']['group']
        room_name = f"char_{min(user.id, int(group))}_{max(user.id, int(group))}"
        async_to_sync(self.channel_layer.group_discard)(room_name, self.channel_name)
        print("断开连接")
        raise StopConsumer()